import { defineStore } from 'pinia'
import { login, register, forgotPassword } from '@/api'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: '',
    userId: '',
    userName: ''
  }),

  getters: {
    // 根据token判断是否登录
    isLoggedIn: (state) => !!state.token
  },

  actions: {
    async loginAction(loginData) {
      const res = await login(loginData)
      // 从data字段中获取数据
      this.token = res.data.token
      this.userId = res.data.userId
      this.userName = res.data.userName
      return res
    },

    async registerAction(registerData) {
      const res = await register(registerData)
      return res
    },

    async forgotPasswordAction(data) {
      const res = await forgotPassword(data)
      // 忘记密码也需要从data中获取
      return res.data
    },

    logout() {
      this.token = ''
      this.userId = ''
      this.userName = ''
    }
  },

  // Pinia持久化配置
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'user',
        storage: localStorage,
        paths: ['token', 'userId', 'userName']
      }
    ]
  }
})